from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Teacher
from .forms import TeacherForm

@login_required
def teacher_list(request):
    from django.core.paginator import Paginator
    teacher_list = Teacher.objects.all()
    paginator = Paginator(teacher_list, 12)  # 每页显示12条记录
    
    page = request.GET.get('page')
    teachers = paginator.get_page(page)
    return render(request, 'teachers/teacher_list.html', {'teachers': teachers})

@login_required
def teacher_detail(request, pk):
    teacher = get_object_or_404(Teacher, pk=pk)
    return render(request, 'teachers/teacher_detail.html', {'teacher': teacher})

@login_required
def teacher_add(request):
    if request.method == 'POST':
        form = TeacherForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '教师信息添加成功！')
            return redirect('teachers:teacher_list')
    else:
        form = TeacherForm()
    return render(request, 'teachers/teacher_form.html', {'form': form, 'title': '添加教师'})

@login_required
def teacher_edit(request, pk):
    teacher = get_object_or_404(Teacher, pk=pk)
    if request.method == 'POST':
        form = TeacherForm(request.POST, instance=teacher)
        if form.is_valid():
            form.save()
            messages.success(request, '教师信息更新成功！')
            return redirect('teachers:teacher_detail', pk=pk)
    else:
        form = TeacherForm(instance=teacher)
    return render(request, 'teachers/teacher_form.html', {
        'form': form,
        'title': f'编辑教师信息 - {teacher.name}',
        'teacher': teacher
    })

@login_required
def teacher_delete(request, pk):
    teacher = get_object_or_404(Teacher, pk=pk)
    if request.method == 'POST':
        teacher.delete()
        messages.success(request, '教师信息已删除！')
        return redirect('teachers:teacher_list')
    return redirect('teachers:teacher_detail', pk=pk)
